<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><router-link to="/reporting/inventory">库存上报管理</router-link></el-breadcrumb-item>
        <el-breadcrumb-item>新增库存上报</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <basic-container>
      <el-form :model="categoryForm" label-width="120px" label-position="right">
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户" required>
              <select-customer-form 
                  :customerObj="{customerName: categoryForm.customerName, customerSn: categoryForm.customerSn}"
                  @changeCustomer="handleSelectCustomer"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上报人员" required>
              <el-select
                filterable
                class="fill-width" 
                remote 
                :remote-method="remoteStaffList"
                v-model="categoryForm.reportManId" 
                style="float: left" 
                placeholder="请选择">
                <el-option
                  v-for="item in teamList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上报位置定位" required>
              <p style="text-align: left">{{reportLocation.formattedAddress}}</p>
              <avue-map v-model="reportLocation" style="width:200px" :lnglat="lnglat"></avue-map>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="销售日期">
              <el-date-picker
                class="fill-width"
                v-model="categoryForm.reportDate"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" required>
              <el-input type="textarea" :maxlength="255" v-model="categoryForm.remarks" style="float: left" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其它金额" required>
              <el-input-number class="fill-width" v-model="categoryForm.otherAmount" style="float: left" placeholder="请输入" :precision="2" @change="countPrice"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品合计金额" required>
              <el-input-number class="fill-width" :disabled="true" v-model="categoryForm.goodsTotalAmount" style="float: left" placeholder="请输入" :precision="2" @change="countPrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总计金额">
              <el-input-number class="fill-width" v-model="categoryForm.totalAmount" style="float: left" placeholder="请输入" :precision="2" @change="countCouponAmount"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠金额">
              <el-input-number class="fill-width" :disabled="true" v-model="categoryForm.couponAmount" style="float: left" placeholder="请输入" :precision="2"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="上报状态">
              <el-select filterable class="fill-width" v-model="categoryForm.reportStatus" style="float: left" placeholder="请选择">
                <el-option
                  v-for="item in data_report_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
          <div style="margin: 10px 40px; text-align: left">
            <el-form :inline="true" class="pocForm" label-width="120px">
                <el-button @click="showGoodsDialog()">添加商品</el-button>
            </el-form>
          </div>
          <el-form-item label-width="0px" style="margin-left: 40px;">
            <el-table
              :data="tableData"
              :header-cell-style="{background:'#eef1f6',color:'#606266'}">
              <el-table-column label="序号" prop="id" align="center" type="index"></el-table-column>
              <el-table-column label="商品销售类型" width="120px">
                <template slot-scope="scope">
                  <el-select @change="countPrice" v-model="scope.row.salesGoodsType">
                    <el-option
                      v-for="item in goodsTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="商品图片" align="center">
                <template slot-scope="scope">
                  <img :src="scope.row.goodsImg" height="50px"/>
                </template>
              </el-table-column>
              <el-table-column label="商品名称" prop="goodsName" align="center"></el-table-column>
              <el-table-column label="规格" min-width="120px" prop="modelName" align="center">
                <template slot-scope="scope">
                  <el-select @change="changeModel(scope.row.goodsModelId, scope.row)" v-model="scope.row.goodsModelId" style="float: left" placeholder="请选择">
                    <el-option
                      v-for="item in scope.row.goodsModelList"
                      :key="item.modelId"
                      :label="item.modelName"
                      :value="item.modelId">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="unit" align="center"></el-table-column>
              <el-table-column label="采购数量" prop="goodsNum" align="center" width="160">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.goodsNum" style="width: 145px" :min="1" :precision="0" :max="20000" label="数量" @change="countPrice"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="交易价格" prop="tradePrice" align="center" width="160">
                <template slot-scope="scope">
                  <el-input-number v-if="scope.row.salesGoodsType === '1'" :disabled="true" v-model="scope.row.commonPrice" style="width: 145px" label="价格" :precision="2"></el-input-number>
                  <el-input-number v-if="scope.row.salesGoodsType === '2'" v-model="scope.row.tradePrice" style="width: 145px" :min="1" :max="20000" label="价格" :precision="2" @change="countPrice"></el-input-number>
                  <el-input-number v-if="scope.row.salesGoodsType === '3'" :disabled="true" :value="0" style="width: 145px" label="价格" :precision="2"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="合计金额" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.salesGoodsType === '1'">{{scope.row.goodsNum * scope.row.commonPrice}}</span>
                  <span v-if="scope.row.salesGoodsType === '2'">{{scope.row.goodsNum * scope.row.tradePrice}}</span>
                  <span v-if="scope.row.salesGoodsType === '3'">0</span>
                </template>
              </el-table-column>
              <el-table-column label="保质期" min-width="100px" prop="expiration" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.expiration" maxlength="10"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="生产日期" prop="productTime" align="center" width="240">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.productTime"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择生产日期">
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="到期日期" prop="maturityTime" align="center" width="240">
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.maturityTime"
                    type="datetime"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择到期日期">
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remarks" align="center" width="200">
                <template slot-scope="scope">
                  <el-input type="textarea" :rows="2" v-model="scope.row.remarks" maxlength="255"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="primary" size="danger" @click="delGood(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="上报图片" required>
              <div v-if="categoryForm.photoList" class="thumbUrl" v-for="(item,index) in categoryForm.photoList">
                <img :src="item.picUrl" />
                <div class="hover_show">
                  <i class="el-icon-delete" @click="handlePictureRemove(index)"></i>
                </div>
              </div>
              <div class="select_img" @click="sel_img()" style="float: left;"><i class="el-icon-plus"></i></div>
              <div v-if="sleImg">
                <el-dialog title="选择图片" :visible.sync="sleImg" style="text-align: left;">
                  <sel-img-photogallery ref="selImg" type="11" @select="onSelectImgs"></sel-img-photogallery>
                </el-dialog>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row :span="24">
          <div style="margin: 10px 50px;text-align: left">
            <el-form :inline="true" class="pocForm" label-width="90px">
                <el-button @click="showGoodsDialog()">添加商品</el-button>
            </el-form>
          </div>
          <el-table
            :data="tableData"
            style="width: 100%;margin-bottom: 15px"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}">
            <el-table-column label="序号" prop="id" align="center" type="index"></el-table-column>
            <el-table-column label="商品图片" align="center">
              <template slot-scope="scope">
                <img :src="scope.row.goodsImg" height="50px"/>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goodsName" align="center"></el-table-column>
            <el-table-column label="规格" prop="modelName" align="center">
              <template slot-scope="scope">
                <el-select v-model="scope.row.modelName" style="float: left" placeholder="请选择">
                  <el-option
                    v-for="item in scope.row.goodsModelList"
                    :key="item.id"
                    :label="item.modelName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="unit" align="center"></el-table-column>
            <el-table-column label="采购数量" prop="goodsNum" align="center" width="160">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.goodsNum" style="width: 145px" :min="1" :max="20000" label="数量" @change="countPrice"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="交易价格" prop="tradePrice" align="center" width="160">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.tradePrice" style="width: 145px" :min="1" :max="20000" label="价格" @change="countPrice"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="保质期" prop="expiration" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.expiration" maxlength="10"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="生产日期" prop="productTime" align="center" width="240">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.productTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择生产日期">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="到期日期" prop="maturityTime" align="center" width="240">
              <template slot-scope="scope">
                <el-date-picker
                  v-model="scope.row.maturityTime"
                  type="datetime"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择到期日期">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remarks" align="center">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remarks" maxlength="10"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="danger" @click="delGood(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row> -->
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="上报图片" required>
              <div v-if="categoryForm.photoList" class="thumbUrl" v-for="(item,index) in categoryForm.photoList">
                <img :src="item.picUrl" />
                <div class="hover_show">
                  <i class="el-icon-delete" @click="handlePictureRemove(index)"></i>
                </div>
              </div>
              <div class="select_img" @click="sel_img()" style="float: left;"><i class="el-icon-plus"></i></div>
              <div v-if="sleImg">
                <el-dialog title="选择图片" :visible.sync="sleImg" style="text-align: left;">
                  <sel-img-photogallery ref="selImg" type="08" @select="onSelectImgs"></sel-img-photogallery>
                </el-dialog>
              </div>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-form-item>
          <div>
            <el-button type="primary" size="medium" @click="save">保存</el-button>
            <el-button type="default" size="medium" @click="close">取消</el-button>
          </div>
        </el-form-item>
        <el-dialog title="选择商品" :visible.sync="dialogVisible">
          <goods-list @select="onSelectGoods"></goods-list>
        </el-dialog>
      </el-form>
    </basic-container>
    
  </div>
</template>

<script>
  import Request from '../../order_con/request.js'
  import {getStore, setStore} from "@/util/store";
  import selImgPhotogallery from '@/components/pds/common/sel_img_photogallery'
  import {
    fetchList,
  } from '@/api/crm/customer'
  import {
    fetchList as teamList,
  } from '@/api/crm/marketemployee' //联系人
  import {
    addReport,
  } from '@/api/crm/rep'
  import AvueMap from 'avue-plugin-map'
  import {
    mapGetters
  } from 'vuex'
  import Vue from 'vue'
  import {fetchDict} from '@/util/util';
  import goodsList from '../../order_con/customerOrder/components/goodsList.vue'
  import moment from 'moment';
  import selectCustomerForm from '@/components/crm/select_customer_form';
  export default {
    data() {
      return {
        request: new Request(),
        categoryForm:{
          photoList:[],
          totalAmount: 0,
          otherAmount: 0,
          couponAmount: 0,
          goodsTotalAmount: 0,
        },
        sleImg:false,
        //初始化坐标
        lnglat: {
          P: 29.563761,
          R: 106.55046400000003,
        },
        goodsTypeList: [{
          label: '普通',
          value: '1',
        }, {
          label: '促销品',
          value: '2',
        }, {
          label: '赠品',
          value: '3',
        }],
        custmoerList:[],
        teamList:[],
        visit_step:[],
        customer_status:[],
        visit_status:[],
        data_report_status: [],
        reportLocation:{
          formattedAddress:'',
          longitude:'',
          latitude:'',
        },
        loading:false,
        selectGoods: {
          goodsName: '',
          loading: '',
          goodsList: [],
          goodsId: '',
          goodsModelList: []
        },
        tableData:[],
        dialogVisible:false
      }
    },
    components: {  
      selImgPhotogallery,
      goodsList,
      selectCustomerForm,
    },
    computed: {
      ...mapGetters(['tagWel', 'tagList', 'tag', 'website']),
      tagLen() {
        return this.tagList.length || 0
      }
    },
    mounted() {

    },
    created(){
      fetchDict('scm_visit_step', this.visit_step);
      fetchDict('scm_customer_status', this.customer_status);
      fetchDict('scm_visit_status', this.visit_status);
      fetchDict('scm_data_report_status', this.data_report_status);
      Vue.use(AvueMap);
      this.getList();
    },
    methods: {
      //获取销售区域
      getList(page, params) {
        this.tableLoading = true
        fetchList({current: 1, size: 1000}).then(response => {
          this.custmoerList = response.data.data.records
        })
        teamList({current: 1, size: 1000}).then(response => {
          this.teamList = response.data.data.records
        })
      },
      async remoteStaffList(name) {
        let query = {};
        if(name) query.name = name;
        let res = await teamList(Object.assign(query, {current: 1, size: 50}));
        this.teamList = res.data.data.records;
      },
      async handleSelectCustomer(customerObj) {
        if(this.categoryForm.customerSn === customerObj.customerSn) return;
        this.$set(this.categoryForm, 'customerSn', customerObj.customerSn);
        this.$set(this.categoryForm, 'customerName', customerObj.customerName);
      },
      changeModel(modelName, row) {
        this.$set(row, 'tradePrice', getPrice(modelName, row.goodsModelList));
        this.$set(row, 'commonPrice', getPrice(modelName, row.goodsModelList));
        this.countPrice();
      },
      sel_img(){
        this.sleImg = true;
      },
      onSelectImgs(imgs){
        imgs.forEach((item)=>{
          this.categoryForm.photoList.push({id:item.id,picUrl:item.picUrl})
        })
        this.sleImg = false;
      },
      // 删除el-upload的图片
      handlePictureRemove(index) {
        this.categoryForm.photoList.splice(index,1)
      },
      showGoodsDialog($event, index) {
        this.dialogVisible = true
        this.selectedRowIndex = index
      },
      onGoodsSelectChange(e, row) {
        if(e){
          let selectedGoods = row.goodsList.filter(item => item.id === e)[0]
          row.goodsModelList = selectedGoods.goodsModelList
          this.$set(row, 'goodsName', selectedGoods.goodsName)
          this.$set(row, 'thumbUrl', selectedGoods.thumbUrl)
        }else{
          // 清空选项时
          this.$set(row, 'goodsId', '');
          row.goodsId = '';
        }
      },
      onSelectGoods(goods) {
        this.dialogVisible = false;
        // this.selectGoods = goods;
        this.addSubmit(goods);
      },
      // 商品选择相关
      searchGoodsByName(row) {
        // 将row信息传入
        let _this = this;
        return function (searchValue) {
          if (searchValue !== '') {
            row.loading = true
            console.log('time', searchValue);
            let params = {
              goodsName: searchValue,
            }
            params.shopId = getStore({name: "shopId"})
            params.pageNo = _this.currentPage
            params.pageSize = _this.pageSize
            params.goodsName = searchValue
            _this.request.getGoodsList(params).then(res => {
              if (res.code == 200) {
                _this.$set(row, 'goodsList', res.ext.list);
                _this.$set(row, 'loading', false);
                _this.goodsList = res.ext.list
                _this.currentPage = res.ext.pageNo
                _this.totalCount = res.ext.count
              } else if (res.code == '983') {
                _this.goodsList = []
              } else {
                _this.$message.error('请求失败')
              }
            })
          }
        }
      },
      addSubmit(goods){
        goods.goodsModelList = goods.goodsModelList.map(item =>{
          item['modelId'] = item.id;
          return item;
        })
        var good = {
          salesGoodsType: '1',
          goodsId:goods.goodsModelList[0].goodsId,
          goodsImg: goods.thumbUrl,
          goodsName: goods.goodsName,
          unit: goods.goodsModelList[0].modelUnit,
          goodsModelList: goods.goodsModelList,
          modelName:goods.goodsModelList[0].modelName,
          goodsNum: 1,
          remarks: '',
          commonPrice: goods.goodsModelList[0].modelPrice,
          tradePrice:goods.goodsModelList[0].modelPrice,
          goodsModelId:goods.goodsModelList[0].id,
          expiration:'一个月',
          productTime: moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
          maturityTime: moment().startOf('day').add(30, 'day').format('YYYY-MM-DD HH:mm:ss'),
        }
        this.tableData.push(good);
        this.countPrice();
      },
      delGood(index){
        this.tableData.splice(index,1);
        this.countPrice();
      },
      countPrice(){
        this.$set(this.categoryForm, 'totalAmount', this.getTotalAmount());
        this.countCouponAmount();
      },
      getTotalAmount() {
        let totalAmount = 0;
        this.tableData && this.tableData.length && this.tableData.map(item => {
          if(item.salesGoodsType === '1') totalAmount += parseFloat(item.goodsNum*item.commonPrice);
          if(item.salesGoodsType === '2') totalAmount += parseFloat(item.goodsNum*item.tradePrice);
        })
        this.$set(this.categoryForm, 'goodsTotalAmount', totalAmount);
        totalAmount += this.categoryForm.otherAmount;
        return totalAmount;
      },
      // 计算优惠价格
      countCouponAmount() {
        let couponAmount = this.getTotalAmount() - this.categoryForm.totalAmount;
        this.$set(this.categoryForm, 'couponAmount', couponAmount);
      },
      //确定
      save(){
        let tmp = []
        this.categoryForm.photoList.forEach((item)=>{
          tmp.push(item.id);
        })
        this.categoryForm.photoList = tmp;
        let params = this.categoryForm;
        params.reportAddress = this.reportLocation.formattedAddress;
        params.reportLocation = (this.reportLocation.longitude && this.reportLocation.latitude) ?this.reportLocation.longitude + ',' + this.reportLocation.latitude:'';
        let detailList = [];
        this.tableData.forEach((item)=>{
          let tradePrice = 0;
          if(item.salesGoodsType === '1') tradePrice = item.commonPrice;
          if(item.salesGoodsType === '2') tradePrice = item.tradePrice;
          detailList.push({
            salesGoodsType: item.salesGoodsType,
            goodsModelId:item.goodsModelId,
            tradePrice: tradePrice,
            goodsNum:item.goodsNum,
            expiration:item.expiration,
            productTime:item.productTime,
            maturityTime:item.maturityTime,
            remarks:item.remarks
          });
        })
        params.detailList = detailList;
        addReport(params).then(response => {
          if(response.data.code == 0){
            this.$message.success('创建成功')
            let _this = this;
            setTimeout(function () {
              _this.close();
            },2000)
          }else{
            this.$message.success(response.data.msg)
          }
        })
      },
      close(){
        var str_before = location.href.split('#')[1];
        let { tag, key } = this.findTag(str_before);
        this.$store.commit('DEL_TAG', tag);
        this.$router.go(-1);
      },
      findTag(value) {
        let tag, key
        this.tagList.map((item, index) => {
          if (item.value === value) {
            tag = item
            key = index
          }
        })
        return { tag: tag, key: key }
      }
    }
  }

function getPrice(modelId, data) {
  let price = 0;
  data.map(item => {
    if(item.modelId === modelId) return price = item.modelPrice;
  })
  return price;
}
</script>

<style scoped lang="scss">
  .crumbs{
    margin: 20px 10px;
  }
  .thumbUrl{
    width: 150px;
    height: 150px;
    position: relative;
    line-height: 146px;
    float: left;
    margin-right: 15px;
    border-radius: 6px;
    overflow: hidden;
    border: 1px solid #c0ccda;
    text-align: center;
  }
  .thumbUrl img{
    width: 100%;
    height: 100%;
  }
  .thumbUrl .hover_show{
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0,0.5);
    width: 100%;
    height: 100%;
    display: none;
  }
  .thumbUrl:hover .hover_show{
    display: block;
  }
  .thumbUrl .hover_show i{
    color: #fff;
    margin: 0 10px;
    cursor: pointer;
  }
  .select_img{
    width: 148px;
    height: 148px;
    line-height: 146px;
    border: 1px dashed #c0ccda;
    background-color: #fbfdff;
    font-size: 28px;
    color: #8c939d;
    cursor: pointer;
    border-radius: 6px;
    text-align: center;
  }
</style>


